from django.contrib import admin
from .models import *
from apps.order.flows import OrderFlow
from django.db import transaction
from tuntun.settings import DJANGO_SUPER_USER_GROUP_NAME, DJANGO_REPO_USER_GROUP_NAME
# Register your models here.

class SubOrderInline(admin.StackedInline):
    model = SubOrder
    fields = ['goods_block_unique_code', 'goods_block_repo_no']
    readonly_fields = fields

class OrderAdmin(admin.ModelAdmin):
    """Order Admin"""
    list_display = ("no", 'product_name', "amount", "payment_method", "status_display",'seller_user', "buyer_user", 'create_type_display', 'as_gift', 'get_add_time', 'get_pay_expire_at', 'get_gift_expire_at', 'post_finished_done')
    list_filter = ('status', 'as_gift', 'create_type')
    fields = ('no', 'express_no', 'address_mobile', 'address_name', 'address_full_address')
    search_fields = ('no',)
    inlines = [SubOrderInline, ]
    def get_readonly_fields(self, request, obj=None):
        return ('address_mobile', 'address_name', 'address_full_address')
    def save_model(self, request, obj, form, change):
        if change:
            express_no = form.cleaned_data['express_no']
            obj.express_no = express_no
            obj.status = Order.Status.FINISHED.name
            obj.save()
            of = OrderFlow(obj)
            of.post_trade_order_finished()
        if obj and obj.express_no:
            obj.status = Order.Status.FINISHED.name
            obj.save()

    def has_add_permission(self, request):
        return False
    def has_delete_permission(self, request, obj=None):
        return False
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.groups.all().filter(name=DJANGO_SUPER_USER_GROUP_NAME):
            pass
        else:
            qs = qs.filter(create_type=Order.CreateType.TAKE_OUT.name)
        return qs
admin.site.register(Order, OrderAdmin)


class PaymentAdmin(admin.ModelAdmin):
    list_display = ('ptype', 'order', 'payment_method', 'status', 'settlement_total_fee', 'order_amount')
    search_fields = ('order__no', )
admin.site.register(Payment, PaymentAdmin)


class ExpressCompanyAdmin(admin.ModelAdmin):
    list_display = ('name', 'code', 'kefu_phone')
    fields = ('name', 'code', 'kefu_phone')
    readonly_fields = ('code', )
admin.site.register(ExpressCompany, ExpressCompanyAdmin)